<template>
  <div class="app">
    <div class="title">
      <!-- 搜索栏部分开始 -->
      <div class="search">
        <div class="block">
          <el-input
            v-model="searchval"
            placeholder="请输入管理员名称"
            clearable
            class="el-inputs"
          ></el-input>
          <el-select v-model="Coutype" placeholder="请选择优惠券类型">
            <el-option
              v-for="item in CouponCtype"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-select v-model="statu" placeholder="请选择优惠券状态">
            <el-option
              v-for="item in CouponsStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        <div class="topinput">
          <el-button
            type="primary"
            icon="el-icon-search"
            class="searchlogo"
            @click="searchvalue"
            >查找</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-edit"
            class="addlogo"
            @click="addmore"
            >添加</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-download"
            class="MoveValue"
            @click.native="download"
            >当前页面导出</el-button
          >
        </div>
      </div>
      <!-- 搜索栏部分结束 -->

      <!-- 表格内容部分开始 -->
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        highlight-current-row
        min-width
      >
        <el-table-column
          prop="id"
          label="优惠券ID"
          align="center"
          sortable
        ></el-table-column>
        <el-table-column
          prop="title"
          label="优惠券名称"
          align="center"
        ></el-table-column>
        <el-table-column prop="type" label="优惠券类型" align="center">
          <template slot-scope="scope">
            <div>{{ scope.row.type == 1 ? "满减券" : "" }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="介绍"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="total"
          label="优惠券数量"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="surplus"
          label="剩余数量"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="limit"
          label="每人限领"
          align="center"
        ></el-table-column>
        <el-table-column prop="discount" label="满减金额" align="center">
          <template slot-scope="scope">
            <div>减免{{ scope.row.discount }}元</div>
          </template>
        </el-table-column>
        <el-table-column prop="min" label="最低消费" align="center">
          <template slot-scope="scope">
            <div>满{{ scope.row.min }}可用</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <el-tag>{{
              time > scope.row.gmtEnd
                ? "已过期"
                : scope.row.status == 1
                ? "正常"
                : "下架"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="使用类目名称" align="center">
          <template slot-scope="scope">
            <el-tag>{{
              scope.row.categoryTitle ? scope.row.categoryTitle : "全部类目"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="categoryId"
          label="使用类目ID"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="days"
          label="领券相对天数"
          align="center"
        ></el-table-column>
        <el-table-column prop="gmtStart" label="领券开始时间" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.gmtStart | gmtStart }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="gmtEnd" label="领券结束时间" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.gmtEnd | gmtEnd }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="activation(scope.row)">
              {{time > scope.row.gmtEnd ? "已过期" : scope.row.status == 1 ? "冻结": "激活"}}
             </el-button>
            <el-button
              size="mini"
              type="primary"
              @click="editor(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              class="editor"
              @click="Delete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格内容部分结束 -->

      <!-- 添加&编辑部分开始 -->
      <el-dialog
        :title="bools ? '创建' : '编辑'"
        :visible.sync="dialogFormVisible"
      >
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
          <!-- 优惠券名称 -->
          <el-form-item
            prop="title"
            label="优惠券名称"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.title"
              autocomplete="off"
              class="DialogInput"
            ></el-input>
          </el-form-item>
          <!-- 优惠券类型 -->
          <el-form-item
            prop="type"
            label="优惠券类型"
            :label-width="formLabelWidth"
            placeholder=""
          >
            <el-select v-model="form.type">
              <el-option
                v-for="item in newcoupon"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 介绍 -->
          <el-form-item
            prop="description"
            label="介绍"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.description"
              autocomplete="off"
              class="DialogInput"
            ></el-input>
          </el-form-item>
          <!-- 优惠券数量 -->
          <el-form-item
            prop="total"
            label="优惠券数量"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.total">
              <template slot="append">张</template>
            </el-input>
          </el-form-item>
          <!-- 每人限领 -->
          <el-form-item
            prop="limit"
            label="每人限领"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.limit">
              <template slot="append">张</template>
            </el-input>
          </el-form-item>
          <!-- 满减金额 -->
          <el-form-item
            prop="discount"
            label="满减金额"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.discount">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <!-- 最低消费 -->
          <el-form-item
            prop="min"
            label="最低消费"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.min">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <!-- 优惠券状态 -->
          <el-form-item
            prop="status"
            label="优惠券状态"
            :label-width="formLabelWidth"
            placeholder=""
          >
            <el-select v-model="form.status">
              <el-option
                v-for="item in couponsstatus"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 有效期 -->
          <el-form-item
            prop="days"
            label="有效期"
            :label-width="formLabelWidth"
            placeholder=""
          >
            <el-button type="primary" plain @click="adddays"
              >领券相对天数</el-button
            >
            <el-button type="primary" plain @click="absolutime"
              >指定绝对时间</el-button
            >
            <div v-if="show">
              <el-form-item
                prop=""
                label=""
                :label-width="formLabelWidth"
                class="shows"
              >
                <el-input v-model="input5">
                  <template slot="append">天</template>
                </el-input>
              </el-form-item>
            </div>
            <div v-else class="allover">
              <div class="block">
                <el-date-picker
                  v-model="value1"
                  type="datetime"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </div>
              <p>至</p>
              <div class="block">
                <el-date-picker
                  v-model="value2"
                  type="datetime"
                  placeholder="选择日期"
                  align="right"
                >
                </el-date-picker>
              </div>
            </div>
          </el-form-item>
          <!-- 商品限制范围 -->
          <el-form-item
            prop="categoryId"
            label="商品限制范围"
            :label-width="formLabelWidth"
          >
            <el-button type="primary" plain @click="general"
              >全场通用</el-button
            >
            <el-button type="primary" plain @click="classification"
              >指定分类</el-button
            >
            <div v-if="count"></div>
            <div v-else class="allover">
              <el-form
                :model="forms"
                ref="forms"
                style="position: relative; padding-top: 10px; right: 120px"
              >
                <el-form-item
                  label="优惠类目"
                  :label-width="formLabelWidth"
                  prop=""
                >
                  <el-cascader
                    v-model="form.name"
                    :options="option"
                    :props="{ expandTrigger: 'hover' }"
                    placeholder="关联商品"
                  ></el-cascader>
                </el-form-item>
              </el-form>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeing('form')">取 消</el-button>
          <el-button type="primary" @click="addlist('form')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 添加&编辑部分结束 -->

      <!-- 分页部分开始 -->
      <div class="paging">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNo"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </div>
      <!-- 分页部分结束 -->
    </div>
  </div>
</template>


<script>
import {
  couponlist,
  deletelist,
  gethave,
  addlister,
  editorlist,
} from "../encapsulation/CouponManagement";
export default {
  data() {
    // 非空验证
    var checks = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("优惠券名称不能为空"));
      } else {
        if (this.form.name !== "") {
          // this.$refs.form.validateField('checkPass');
        }
        callback();
      }
    };
    return {
      value: [], //spu树
      option: [], //spu树
      forms: { name: "", region: "" }, //form表单内容
      dialogFormVisible: false, //点击隐藏添加对话框
      bools: true, //判断弹框的布尔值
      show: true, //有效期
      time: 0,
      count: true, //商品限制范围
      formLabelWidth: "120px",
      label: "",
      tableData: [], //渲染列表的数组
      value1: "",
      value2: "",
      input1: "", //优惠券数量
      input2: "", //每人限领
      input3: "", //满减金额
      input4: "", //最低消费
      input5: "", //领券相对天数
      Coutype: "", //优惠券类型
      CouStatu: "", //优惠券状态
      searchval: "", //搜素框输入的值
      pageNo: 1, // 默认页数
      pageSize: 20, // 页面条数
      total: 0, // 总共条数
      settime: new Date(), //获取当前时间
      getTime: [], //获取时间
      nums: [], //类目树
      statu: "undefined",
      newcoupon: [
        //优惠券类型
        {
          value: "1",
          label: "满减卷",
        },
      ],
      couponsstatus: [
        {
          value: "1",
          label: "正常",
        },
        {
          value: "2",
          label: "下架",
        },
      ],
      CouponCtype: [
        //优惠券状态
        {
          value: "满减卷",
          label: "满减卷",
        },
        {
          value: "全部",
          label: "全部",
        },
      ], //优惠券类型
      CouponsStatus: [
        {
          value: "下载",
          label: "下载",
        },
        {
          value: "正常",
          label: "正常",
        },
        {
          value: "已过期",
          label: "已过期",
        },
        {
          value: "全部",
          label: "全部",
        },
      ], //优惠券状态
      // 弹框的内容
      form: {
        id: "",
        title: "",
        type: "1",
        description: "",
        total: 0,
        limit: 0,
        discount: 0,
        min: 0,
        status: 1,
        days: "",
        discounts: "",
        categoryId: undefined,
      },
      rules: {
        title: [
          {
            validator: checks,
            trigger: "blur",
            required: true,
          },
        ],
        type: [
          {
            required: true,
            message: "请选择优惠券类型",
            trigger: "change",
          },
        ],
        total: [
          {
            required: true,
            message: "请输入优惠券数量",
            trigger: "blur",
          },
          {
            pattern: /^[0-9]\d*$/,
            message: "请输入整数",
          },
        ],
        limit: [
          {
            required: true,
            message: "请输入优惠券数量",
            trigger: "blur",
          },
          {
            pattern: /^[0-9]\d*$/,
            message: "请输入整数",
          },
        ],
        discount: [
          {
            required: true,
            message: "请输入优惠券数量",
            trigger: "blur",
          },
          {
            pattern: /^[0-9]\d*$/,
            message: "请输入整数",
          },
        ],
        min: [
          {
            required: true,
            message: "请输入优惠券最低价格",
            trigger: "blur",
          },
          {
            pattern: /^[0-9]\d*$/,
            message: "请输入整数",
          },
        ],
        status: [
          {
            required: true,
            message: "请选择优惠券类型",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    // 激活
    activation(row) {
      if (this.time > row.gmtEnd) {
        if (document.getElementsByClassName("el-message").length === 0) {
          this.$message.error("优惠券已过期建议删除");
        }
      } else {
        let statu = row.status == 1 ? (row.status = 0) : (row.status = 1);
        let data = {
          id: row.id,
          status: row.status,
        };
        editorlist(data).then((res) => {
          if (res.data.errno == 200) {
            this.$message({
              type: "success",
              message: "状态更改成功!",
            });
          }
        });
      }
    },
    searchvalue() {
      (this.pageNo = 1), (this.pageSize = 20), this.getlist();
    },
    // 有效期
    adddays() {
      this.show = true;
    },
    absolutime() {
      this.show = false;
    },
    // 商品限制范围
    general() {
      this.count = true;
    },
    classification() {
      this.count = false;
    },
    //获取角色列表
    getlist() {
      let roleLister = {
        pageNo: this.pageNo,
        limit: this.pageSize,
      };
      couponlist(roleLister).then((res) => {
        this.tableData = res.data.data.items;
        // this.total = res.data.data.total;
      });
      gethave().then((res) => {
        //类目树
        console.log(res);
        this.nums = res.data.data;
        this.option = this.nums;
      });
    },
    // 点击取消
    closeing(formName) {
      this.dialogFormVisible = false;
      this.$refs[formName].resetFields();
    },
    // 添加&编辑
    addlist(form) {
      let _this = this;
      if (_this.bools) {
        // 点击添加
        _this.$refs[form].validate((valid) => {
          if (valid) {
            let data = {
              title: _this.form.title, //优惠券名称
              type: _this.form.type, //优惠券类型
              description: _this.form.description, //介绍
              total: _this.form.total, //优惠券数量
              limit: _this.form.limit, //每人限领
              discount: _this.form.discount, //满减金额
              min: _this.form.min, //最低消费
              status: _this.form.status, //优惠券状态
              days: _this.form.days, //优惠时长
            };
            addlister(data).then((res) => {
              if (res.data.errmsg === "系统未知异常") {
                _this.$message.error("优惠券已存在！");
              }
              if (res.data.errmsg === "成功") {
                (_this.dialogFormVisible = false), console.log(res);
                _this.$message({
                  message: "添加成功",
                  type: "success",
                });
                _this.getlist();
              }
              _this.$refs[form].resetFields();
            });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      } else {
        // 编辑
        let data = {
          surplus: _this.form.surplus,
          id: _this.form.id,
          title: this.form.title, //优惠卷标题
          type: this.form.type, //优惠卷类型
          status: this.form.status, //优惠卷状态
          description: this.form.description, //优惠卷描述
          limit: this.form.limit, //用户限制领取
          total: this.form.total, //优惠卷总数
          min: this.form.min, //满足优惠的最低价格
          discount: this.form.discount, //优惠价格
          days: this.form.days, //优惠时长
        };
        editorlist(data).then(() => {
          _this.getlist();
          _this.$message({
            message: "更新成功",
            type: "success",
          });
          _this.dialogFormVisible = false;
          _this.$refs[form].resetFields();
        });
      }
    },
    // 添加弹框
    addmore() {
      this.bools = true;
      this.dialogFormVisible = true;
      this.form.id = ""; //优惠券id
      this.form.title = ""; //优惠券名称
      this.form.type = ""; //优惠券类型
      this.form.description = ""; //介绍
      this.form.total = ""; //优惠券数量
      this.form.limit = ""; //每人限领
      this.form.discount = ""; //满减金额
      this.form.min = ""; //最低消费
      this.form.status = ""; //优惠券状态
    },
    // 编辑弹框
    editor(index, row) {
      this.bools = false;
      this.dialogFormVisible = true;
      this.form.id = row.id; //优惠券id
      this.form.title = row.title; //优惠券名称
      this.form.type = row.type; //优惠券类型
      this.form.description = row.description; //介绍
      this.form.total = row.total; //优惠券数量
      this.form.limit = row.limit; //每人限领
      this.form.discount = row.discount; //满减金额
      this.form.min = row.min; //最低消费
      this.form.status = row.status; //优惠券状态
      this.form.surplus = row.surplus; //优惠券剩余
    },
    // 删除
    Delete(index, row) {
      let _this = this;
      let data = {
        id: row.id,
      };
      _this
        .$confirm(
          "此操作将永久删除该优惠券---" + row.title + "---, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
        .then(() => {
          deletelist(data).then(() => {
            _this.tableData.splice(index, 1);
            this.$message({
              message: "删除成功",
              type: "success",
            });
          });
          this.getlist();
        })
        .catch(() => {
          this.$message("您已取消删除");
        });
    },
    // 下载excel表格
    download() {
      let that = this;
      let tHeader = [
        "优惠券ID",
        "名称",
        "介绍",
        "类型",
        "最低消费",
        "减免金额",
        "每人限领",
        "优惠券数量",
        "剩余数量",
        "状态",
        "使用类目",
      ];

      let add = [
        "id",
        "title",
        "description",
        "type",
        "min",
        "discount",
        "limit",
        "total",
        "surplus",
        "status",
        "categoryTitle",
      ];
      let arr = that.getdownload(add, this.tableData);
      import("../encapsulation/Export2Excel.js").then((excel) => {
        excel.export_json_to_excel({
          header: tHeader, //表头 必填
          data: arr, //具体数据 必填
          filename: "excel-list", //非必填
          autoWidth: true, //非必填
          bookType: "xlsx", //非必填
        });
      });
    },
    getdownload(f, d) {
      return d.map((item) => f.map((j) => item[j]));
    },
    //分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.getlist();
    },
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getlist();
    },
  },
  created() {
    this.getlist();
  },
  watch: {
    dialogFormVisible() {
      if (!this.dialogFormVisible) {
        this.form.title = "";
        this.form.description = "";
        this.form.total = 0;
        this.form.limit = 0;
        this.form.min = 0;
        this.form.discount = 0;
        this.today = "领劵相对天数";
        this.getTime = [];
        this.allday = "全场通用";
        this.form.option = "";
        this.form.days = "";
        this.form.categoryId = [];
        this.$nextTick(() => {
          this.$refs["form"].clearValidate();
        });
      }
    },
    today() {
      if (this.today != "领劵相对天数") {
        this.form.days = "";
      }
    },
  },
  // 过滤
  filters: {
    gmtStart(value) {
      if (!value) {
        return "无";
      } else {
        var date = new Date(value); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + "-";
        var M =
          (date.getMonth() + 1 < 10
            ? "0" + (date.getMonth() + 1)
            : date.getMonth() + 1) + "-";
        var D = date.getDate() + "";
        var h = date.getHours() + ":";
        var m = date.getMinutes() + ":";
        var s = date.getSeconds();
        return Y + M + D + h + m + s;
      }
    },
    gmtEnd(value) {
      if (!value) {
        return "无";
      } else {
        var date = new Date(value); //时间戳为10位需*1000
        var Y = date.getFullYear() + "-";
        var M =
          (date.getMonth() + 1 < 10
            ? "0" + (date.getMonth() + 1)
            : date.getMonth() + 1) + "-";
        var D = date.getDate() + "";
        var h = date.getHours() + ":";
        var m = date.getMinutes() + ":";
        var s = date.getSeconds();
        return Y + M + D + h + m + s;
      }
    },
  },
};
</script>
<style scoped lang="less">
.shows /deep/ .el-form-item__content {
  margin-left: 0px !important;
  margin-top: 20px;
}
.app {
  padding: 20px;
  height: 100%;
  overflow: hidden !important;
  position: relative;
}
.title {
  position: absolute;
  left: 0;
  top: 0;
  right: -17px;
  bottom: 0;
  overflow-x: hidden;
  overflow-y: scroll;
  padding: 20px;
}

.paging {
  padding: 10px 0;
}
.search {
  display: flex;
}
.el-input {
  width: 200px;
}
.topinput {
  display: flex;
  padding-left: 10px;
}
.search {
  padding: 20px;
  align-items: center;
}
.block {
  padding: 0 5px;
}
.el-inputs {
  padding: 0 5px;
}
.el-table {
  font-size: 12px;
}
.allover {
  display: flex;
  align-items: center;
}
</style>
